<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once ($includePath.'/config/cfg.php');
  //require($includePath.'/constants.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
  //require($includePath.'/agi/agifunction.php');
/*********************** INITIALIZATION ***************************************/

  $agi = new AGI();
  // Get AGI parameters 
  // (WARNING: GET array may be null in many cases, parseArgv take $_SERVER content) 
  parse_str($_SERVER["argv"][1], $var_GET);
  $triggeredRuleId=$var_GET["rule"];
  $triggeredEntityId=$var_GET["entity"];
  $triggeredAnswered=$var_GET["answered"];
  $triggeredChannelId=$var_GET["channel"];
  // Extract caller Id
  $triggeredCallerid=$agi->get_variable("CALLERID");
  $triggeredCallerid=$triggeredCallerid["data"];
  preg_match("/(?:\"(.*)\"|(\s*))\s*(?:\<(.*)\>|(.*))/", $triggeredCallerid, $matches);
  $triggeredCallername = $matches[1];
  if ($matches[3]) $triggeredCallerid = $matches[3];
  else if ($matches[4]) $triggeredCallerid = $matches[4];
  else $triggeredCallerid = "ANONYMOUS";
  agiError("-----------------------------------------------");
  agiError("Incoming Rule Set: [$triggeredRuleId] (callerid: $triggeredCallerid)");
  agiError("-----------------------------------------------");

/*********************** PAGE LOGIC ********************************************/
  
  $canContinue=true;
  $qry="SELECT * FROM cw_rule_incoming WHERE rule=$triggeredRuleId ORDER BY priority";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $id=$arr["id"];
    $rule=$arr["rule"];
    $priority=$arr["priority"];
    $timesegment=$arr["timesegment"];
    $callertype=$arr["callertype"];
    $callerid=$arr["callerid"];
    $channel=$arr["from_channel"];
    $number=$arr["from_number"];
    $numberArr=split("\|",$number);
    $macro=$arr["macro"];
    $parameter=$arr["parameter"];
    $duration=$arr["duration"];
    agiError("Rule: $id (Type:$callertype, callerid: $callerid, channel: $channel)");

    //fetch the entity type    
    if ($triggeredEntityId!="") {
      $qry="SELECT * FROM cw_channel WHERE `key`=$triggeredEntityId";
      $resT=$db->Execute($qry);
      $t=$resT->FetchRow();
      $channelId=$t["id"];
    } else $channelId=$triggeredChannelId;
    
    //check rule
    if  ( 
          (
            //(now we are in the rule's timesegment)
            (checkTime($timesegment)===true)
          )
          AND 
          (
            //(rule match all numbers)
            ($number=="") OR 
            //(rule match some number) and (one of them is the triggered one)
            ($number!="" AND in_array($triggeredAnswered,$numberArr)) OR  
            // ??????????? some numbers are dialed and a catch all matched ????????????
            (in_array("X",$numberArr) AND $triggeredAnswered!="s" )  
          )
          AND
          (
            //(rule match all channels) or ((rule match a channel) and (it is the triggered one))
            (($channel==0) OR ($channel!=0 AND $channel==$channelId))
          ) 
          AND
          (
            //no rules has been triggered before
            ($canContinue===true)
          )
        ) 
    {
      //check caller id
      agiError("  TRIGGERED RULE $id!");
      $match=false;
      switch ($callertype) {
          case CALLER_ALL:
            agiError("    --> match for all pattern");
            $match=true;
          break;
          case CALLER_ANONYMOUS:
            if($triggeredCallerid=="ANONYMOUS") {
              agiError("    --> search for pattern ANONYMOUS : ! MATCH !");
              $match=true;
            } else { 
              $match=false;
              agiError("    --> search for pattern ANONYMOUS : NO MATCH");
            }
          break;
          case CALLER_ID:
            if($triggeredCallerid==$callerid){
              agiError("    --> search for pattern $callerid : ! MATCH !");
              $match=true;
            } else {
              agiError("    --> search for pattern $callerid : NO MATCH");
              $match=false;
            }
          break;
          case CALLER_CLASS:
            $match=false;
            $match=_isIncluded($triggeredCallerid,$callerid,0,true); 
          break;
          case CALLER_GROUP:
            $match=false;
            $match=_isIncluded($triggeredCallerid,0,$callerid,true); 
          break;
          default:
            agiError("ERROR: unknown callertype in incoming.inc");
          break;
      }
      if($match===true){   
        // execute macro
        $arrMacro=prepareMacro($macro,$parameter);      
        agiError("  Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
        $agi->exec("macro ".$arrMacro[0].$arrMacro[1]);
        // set canContinue
        if ($duration=="1") $canContinue=true; else $canContinue=false;
      }else{
        agiError("  SKIPPED: callerId doesn't match");
        $canContinue=true;
      }
    }  
  }
  agiError("Exit from incoming.php");
      
?>
